import React, {Component} from "react";
import {connect} from "dva";
import time, {currentTime, dateFormat, getMockTime} from "@/utils/time";
import echarts from "echarts";
import {addResizeHook} from "@/utils/resize";
import {Button, Table, Drawer} from 'antd';
import {Card, Col, Row, DatePicker} from "antd";
import moment from 'moment';
import styles from "@/pages/GaoLu/components/AutoScore/index.less";
import {PageHeaderWrapper} from "@ant-design/pro-layout";

const {RangePicker} = DatePicker;


class ParamStatus extends Component {
  state = {
    visible: true,
    placement: 'right',
    // timeBetween: [time.getStartOfDay(), time.getEndOfDay()],
    data: [],
    chart: null,
    itemNum: 100,
    startTime: time.getStartOfDay(),
    endTime: time.getEndOfDay(),
    defaultStartTime: time.getStartOfDay(),
    defaultEndTime: time.getEndOfDay(),
    option: {
      dataset: {
        source: [
          ['name', 'perc']
        ]
      },
      grid: {
        top: '3%',
        left: '3%',
        right: '4%',
        bottom: '6%',
        containLabel: true
      },
      xAxis: [{
        type: "value",
        // name: "%",
        min: 0,
        max: 100,
        axisLabel: {
          formatter: "{value} %"
        }
      }],
      yAxis: {type: 'category'},
      series: [
        {
          type: 'bar',
          barWidth: 14, // 固定柱子宽度
          encode: {
            // Map the "amount" column to X axis.
            x: 'perc',
            // Map the "product" column to Y axis
            y: 'name'
          },
          label: {
            show: true,
          },
        }
      ]
    },
    moreOption: {
      dataset: {
        source: [
          ['name', 'perc']
        ]
      },
      grid: {
        top: '3%',
        left: '3%',
        right: '4%',
        bottom: '6%',
        containLabel: true
      },
      xAxis: [{
        type: "value",
        // name: "%",
        min: 0,
        max: 100,
        axisLabel: {
          formatter: "{value} %"
        }
      }],
      yAxis: {type: 'category'},
      series: [
        {
          type: 'bar',
          barWidth: 14, // 固定柱子宽度
          encode: {
            // Map the "amount" column to X axis.
            x: 'perc',
            // Map the "product" column to Y axis
            y: 'name'
          },
          label: {
            show: true,
          },
        }
      ]
    }
  };

  async componentDidMount() {

    const payload = await getMockTime("GaoLu")
    this.setState({startTime:payload.start,endTime:payload.end,
      defaultStartTime:payload.start,defaultEndTime:payload.end})

    //make it better
    //发送API 请求
    //! TODO 后端修改，异常值为0的参数，不要传了！！
    this.getStatus();

    // 基于准备好的dom，初始化echarts实例
    this.state.chart = echarts.init(document.getElementById("paramStatus"));
    // 绘制图表
    this.state.chart.setOption(this.state.option);
    addResizeHook(this, this.state.chart.resize)

    this.state.moreChart = echarts.init(document.getElementById("more"));
    // 绘制图表
    this.state.moreChart.setOption(this.state.moreOption);
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const {paramStatus} = nextProps;

    if (paramStatus !== null && paramStatus !== undefined && prevState.chart !== null) {
      // 获取数据副本
      let mapped = paramStatus.map(item=>{return [item[0],item[1].toFixed(2)]});
      const data = mapped.concat();
      // 添加头部
      const d = data.slice(data.length - 10, data.length);
      d.splice(0, 0, ['name', 'score']);
      prevState.option.dataset.source = d;
      prevState.chart.setOption(prevState.option);
      prevState.data = mapped;


      const more = mapped.concat().slice(0,data.length - 10);
      more.splice(0, 0, ['name', 'score']);
      prevState.moreOption.dataset.source = more;

      prevState.moreChart.setOption(prevState.moreOption);
    }
    //state 不需要更改
    return null
  }

  timePick = (value) => {
    this.state.startTime = value[0].toDate();
    this.state.endTime = value[1].toDate();
    this.getStatus()
  };

  refresh = () => {
    this.state.startTime = this.state.defaultStartTime;
    this.state.endTime = this.state.defaultEndTime;
    this.getStatus()
  };


  getStatus = () => {
    const payload = {
      start: dateFormat(this.state.startTime),
      end: dateFormat(this.state.endTime),
      display_item_num: this.state.itemNum
    };
    this.props.dispatch({
      type: 'gaolu/getLoseStatsEffect',
      payload
    });
  };

  showDrawer = () => {
    this.setState({
      visible: !this.state.visible,
    });
  };

  onClose = () => {
    this.setState({
      visible: 'block',
    });
  };


  render() {
    const {
      width = 100,
      height = 300
    } = this.props;

    const {startTime, endTime, data, defaultStartTime, defaultEndTime,visible} = this.state;
    const dateFormat = 'YYYY-MM-DD HH:mm:ss';

    const columns = [

      {title: '剩余指标', dataIndex: 'tag', key: 'tag'},
      {title: '指标', dataIndex: 'value', key: 'value'},
    ];



    return (

      <div>
        <Col span={12}>
          <Card bordered={false}>
              <Row>
                <RangePicker
                  showTime={{format: 'HH'}}
                  format={dateFormat}
                  style={{width: 400}}
                  placeholder={['开始时间', '结束时间']}
                  onOk={this.timePick}
                  key={Math.random()}
                  defaultValue={[moment(defaultStartTime, dateFormat), moment(defaultEndTime, dateFormat)]}
                />
                <Button style={{marginLeft: 10}} size={"small"} onClick={this.refresh}>刷新</Button>
              </Row>
              <Row>
                  <div id="paramStatus" style={{width: `${width}%`, height}}/>
                  <div>
                    <Row style={{marginTop: 30}}>
                      <a className={styles.showMore} style={{float: 'right'}} onClick={this.showDrawer}>{this.state.visible?"显示更多":"收起"}</a>
                    </Row>
                  </div>

              </Row>
          </Card>
      </Col>
        <Col span={12}>
          <Card bordered={false}
                className={styles.moreStatus}
                style={{visibility:visible?"hidden":null,marginLeft:15}}>
            <div id="more" style={{width: `${width}%`, height:900}}/>
          </Card>
        </Col>
      </div>

    )
  }
}


export default connect(({gaolu, global}) => ({
  paramStatus: gaolu.paramStatus,
  global
}))(ParamStatus);
